<template>
  <div class="container">
    <!-- 页面标题 -->
    <div class="page-title text-center mb-6">
      <h2 class="text-2xl md:text-3xl font-bold text-primary relative inline-block">
        文件上传与代码下载中心
        <span class="absolute -bottom-2 left-1/2 transform -translate-x-1/2 w-24 h-1 bg-gradient-to-r from-primary to-indigo-500 rounded-full"></span>
      </h2>
    </div>
    
    <div class="content-wrapper flex flex-col lg:flex-row gap-6">
      <!-- 原有上传区域 -->
      <div class="upload-section w-full lg:w-1/3 p-5 bg-white rounded-xl shadow-md transform transition-all duration-300 hover:shadow-lg">
        <h3 class="section-title text-xl font-semibold mb-4 flex items-center">
          <i class="el-icon-upload2 mr-2 text-primary"></i>文件上传
        </h3>
        <div class="upload-container">
          <!-- ElementUI上传组件 -->
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleUpload" 
            :on-success="onUploadSuccess" 
            :on-error="onUploadError" 
            :before-upload="beforeUpload" 
            :limit="1"
            accept=".jpg,.jpeg,.png,.pdf" 
          >
            <el-button size="small" type="primary" class="upload-btn">
              <i class="el-icon-plus mr-1"></i>点击上传
            </el-button>
            <div slot="tip" class="el-upload__tip">
              支持jpg、jpeg、png、pdf格式，文件大小不超过10MB
            </div>
          </el-upload>

          <!-- 上传成功后展示文件信息 -->
          <div v-if="uploadedFile" class="file-info mt-4 p-3 border rounded bg-light">
            <div class="file-name mb-2">
              <span class="font-medium">文件名：</span>
              <span>{{ uploadedFile.name }}</span>
            </div>
            <div class="file-url flex items-center">
              <span class="font-medium mr-2">文件地址：</span>
              <el-input 
                v-model="uploadedFile.url" 
                class="url-input flex-1" 
                readonly
                :placeholder="uploadedFile.url"
              ></el-input>
              <el-button 
                size="mini" 
                type="text" 
                icon="el-icon-document-copy"
                @click="copyUrl"
                class="ml-2 copy-btn"
              >
                复制
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 项目资源信息与下载区域 -->
      <div class="resource-section w-full lg:w-2/3 p-6 rounded-2xl shadow-xl transform transition-all duration-500 hover:shadow-2xl relative overflow-hidden group">
        <!-- 背景装饰 -->
        <div class="absolute inset-0 bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50 opacity-80 group-hover:opacity-100 transition-opacity duration-700"></div>
        <div class="absolute top-0 right-0 w-64 h-64 bg-indigo-100 rounded-full filter blur-3xl opacity-60 group-hover:opacity-80 -mr-20 -mt-20 transition-all duration-700"></div>
        <div class="absolute bottom-0 left-0 w-64 h-64 bg-pink-100 rounded-full filter blur-3xl opacity-60 group-hover:opacity-80 -ml-20 -mb-20 transition-all duration-700"></div>
        
        <!-- 代码装饰元素 -->
        <div class="absolute top-10 right-10 text-7xl text-indigo-200 opacity-20 rotate-12 group-hover:opacity-30 transition-opacity duration-500 pointer-events-none">
          <i class="el-icon-code"></i>
        </div>
        <div class="absolute bottom-10 left-10 text-6xl text-purple-200 opacity-20 -rotate-12 group-hover:opacity-30 transition-opacity duration-500 pointer-events-none">
          <i class="el-icon-file-code"></i>
        </div>
        
        <!-- 内容 -->
        <div class="panel-header mb-6 relative z-10">
          <h3 class="section-title text-2xl font-bold flex items-center text-indigo-700">
            <i class="el-icon-code-fork mr-2 text-indigo-500 animate-pulse"></i>项目资源下载
          </h3>
          <p class="text-sm text-gray-600 mt-1">获取完整项目代码与资源</p>
        </div>
        
        <!-- 项目信息展示 -->
        <div class="project-info mb-6 p-4 bg-white bg-opacity-70 rounded-lg shadow-sm relative z-10">
          <h4 class="text-xl font-semibold text-gray-800 mb-2">{{ projectInfo.projectName || '项目名称' }}</h4>
          <div class="flex flex-wrap gap-4 text-sm text-gray-600 mb-3">
            <div class="flex items-center">
              <i class="el-icon-time mr-1 text-gray-400"></i>
              <span>创建时间：{{ projectInfo.createdTime || '未知' }}</span>
            </div>
            <div class="flex items-center">
              <i class="el-icon-refresh mr-1 text-gray-400"></i>
              <span>更新时间：{{ projectInfo.updatedTime || '未知' }}</span>
            </div>
            <div class="flex items-center">
              <i class="el-icon-check-circle mr-1 text-green-500" v-if="projectInfo.isValid === 1"></i>
              <i class="el-icon-close-circle mr-1 text-red-500" v-else></i>
              <span>{{ projectInfo.isValid === 1 ? '有效资源' : '已失效' }}</span>
            </div>
          </div>
          <div class="project-description text-gray-700 text-sm leading-relaxed">
            <p class="font-medium mb-1">项目描述：</p>
            <p>{{ projectInfo.description || '暂无项目描述信息' }}</p>
          </div>
        </div>
        
        <!-- 下载按钮区域 -->
        <div class="download-buttons grid gap-5 relative z-10">
          <!-- 下载前端Vue代码按钮 -->
          <el-button 
            type="success" 
            size="medium" 
            class="download-btn group relative overflow-hidden"
            :disabled="!projectInfo.vueUrl"
            @click="downloadFile(projectInfo.vueUrl, '前端Vue代码')"
          >
            <span class="absolute inset-0 bg-success bg-opacity-20 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300 origin-left"></span>
            <i class="el-icon-laptop mr-2"></i>点击下载前端Vue代码
            <span class="absolute right-0 transform translate-x-full group-hover:translate-x-0 transition-transform duration-300 ml-2">→</span>
          </el-button>
          
          <!-- 下载后端SpringBoot代码按钮 -->
          <el-button 
            type="primary" 
            size="medium" 
            class="download-btn group relative overflow-hidden"
            :disabled="!projectInfo.springbootUrl"
            @click="downloadFile(projectInfo.springbootUrl, '后端SpringBoot代码')"
          >
            <span class="absolute inset-0 bg-primary bg-opacity-20 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300 origin-left"></span>
            <i class="el-icon-server mr-2"></i>点击下载后端SpringBoot代码
            <span class="absolute right-0 transform translate-x-full group-hover:translate-x-0 transition-transform duration-300 ml-2">→</span>
          </el-button>
          
          <!-- 下载SQL文件按钮 -->
          <el-button 
            type="warning" 
            size="medium" 
            class="download-btn group relative overflow-hidden"
            :disabled="!projectInfo.sqlUrl"
            @click="downloadFile(projectInfo.sqlUrl, 'SQL文件')"
          >
            <span class="absolute inset-0 bg-warning bg-opacity-20 transform scale-x-0 group-hover:scale-x-100 transition-transform duration-300 origin-left"></span>
            <i class="el-icon-database mr-2"></i>点击下载SQL文件
            <span class="absolute right-0 transform translate-x-full group-hover:translate-x-0 transition-transform duration-300 ml-2">→</span>
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { Message } from 'element-ui';
import { getToken } from '@/utils/auth.js';
import { getResources } from '@/api/Resources.js';

export default {
  data() {
    return {
      uploadedFile: null, // 存储上传成功的文件信息
      tempFileName: '',   // 临时存储文件名
      projectInfo: {}     // 存储项目资源信息
    };
  },
  created(){
    this.initUrl();
  },
  methods: {
    /**
     * 初始化项目资源URL
     * 调用getResources接口获取项目资源信息并存储到data中
     */
    initUrl(){
      getResources(1)
        .then(response => {
          const { code, data, msg } = response;
          if (code === 200 && data) {
            this.projectInfo = data;
          } else {
            Message.warning(`获取资源信息失败：${msg || '未知错误'}`);
            console.warn('资源信息获取失败', response);
          }
        })
        .catch(error => {
          Message.error('获取资源信息时发生网络错误');
          console.error('资源信息请求失败', error);
        });
    },

    // 上传前校验（文件类型、大小）
    beforeUpload(file) {
      const isAllowedType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isAllowedType) {
        Message.error('仅支持jpg、jpeg、png、pdf格式的文件！');
        return false;
      }
      if (!isLt10M) {
        Message.error('文件大小不能超过10MB！');
        return false;
      }
      return true;
    },

    // 自定义上传方法
    handleUpload(option) {
      const file = option.file;
      const formData = new FormData();
      formData.append('file', file);

      // 保存文件名，用于上传成功后展示
      this.tempFileName = file.name;

      axios.post('/system/upload', formData, {
        baseURL: 'http://localhost:8080',
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': getToken(),
          'Authorization': 'Bearer ' + getToken()
        }
      })
        .then(response => {
          option.onSuccess(response.data);
        })
        .catch(error => {
          option.onError(error);
        });
    },

    // 上传成功回调
    onUploadSuccess(response) {
      // 保存文件信息
      this.uploadedFile = {
        name: this.tempFileName,
        url: response
      };
      Message.success('上传成功！');
    },

    // 上传失败回调
    onUploadError(error) {
      this.uploadedFile = null; // 清除可能的文件信息
      Message.error('上传失败：' + (error.response?.data?.message || '网络异常'));
      console.error('上传错误详情：', error);
    },

    // 复制URL到剪贴板
    copyUrl() {
      if (!this.uploadedFile?.url) return;
      
      // 创建临时文本区域用于复制
      const textarea = document.createElement('textarea');
      textarea.value = this.uploadedFile.url;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      
      Message.success('URL已复制到剪贴板！');
    },

    /**
     * 下载文件方法
     * @param {string} url - 下载地址
     * @param {string} fileName - 文件名称描述
     */
    downloadFile(url, fileName) {
      if (!url) {
        Message.warning(`${fileName}下载地址未配置`);
        return;
      }
      
      // 创建a标签进行下载
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.download = ''; // 让浏览器自动处理文件名
      document.body.appendChild(link);
      
      // 添加点击动画效果
      link.click();
      Message.success(`正在下载${fileName}...`);
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(link);
      }, 100);
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.page-title {
  padding: 10px 0;
}

.content-wrapper {
  align-items: stretch;
}

.section-title {
  position: relative;
  padding-bottom: 8px;
}

.section-title::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: 0;
  width: 40px;
  height: 2px;
}

.upload-section .section-title::after {
  background-color: #409eff;
}

.resource-section .section-title::after {
  background-color: #6366f1;
}

.upload-btn {
  transition: all 0.3s ease;
}

.upload-btn:hover {
  transform: translateY(-2px);
}

.file-info {
  transition: all 0.3s ease;
  animation: fadeIn 0.5s;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.copy-btn {
  transition: all 0.2s ease;
}

.copy-btn:hover {
  color: #409eff;
  transform: scale(1.1);
}

.resource-section {
  position: relative;
  overflow: hidden;
}

.download-buttons {
  padding: 10px 0;
}

.download-btn {
  height: 55px;
  font-size: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.download-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.download-btn:disabled {
  opacity: 0.7;
  transform: none;
  cursor: not-allowed;
}

.project-info {
  transition: all 0.3s ease;
}

.bg-light {
  background-color: #f5f7fa;
}

.font-medium {
  font-weight: 500;
}

.url-input {
  width: auto;
}

@media (max-width: 1024px) {
  .content-wrapper {
    flex-direction: column;
  }
}

@media (max-width: 768px) {
  .download-btn {
    font-size: 14px;
  }
  
  .project-info {
    padding: 3px;
  }
  
  .project-description {
    font-size: 13px;
  }
}
</style>